package com.deloitte.service.rest.jersy;

import java.io.File;
import java.util.*;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import com.deloitte.model.SlideInfo;
import com.deloitte.util.StringUtilities;

@Path("getslides")
public class SlideInfoService {
	
	private static final Map<String, ArrayList<SlideInfo>>  slideMap = new HashMap<String, ArrayList<SlideInfo>>();
	private static final String rootPath = FileUploadController.getRootPath();
	private static final String indexSeperator = FileUploadController.getIndexSeperator();
	
	public static ArrayList<SlideInfo> getSlides(String catalogCode){
		//load slides if it is empty
		if(slideMap.isEmpty()){
			loadSlides();
		}
		ArrayList<SlideInfo> slides = null;
		if(!StringUtilities.isEmpty(catalogCode)){
			slides = slideMap.get(catalogCode);
		}
		return slides;
	}
	
	public static void loadSlides(){
		
		slideMap.clear();
		//Read all the files in this location
		File file = new File(rootPath);
		if(file.exists() && file.isDirectory()){
			File[] catalogs = file.listFiles();
			if(catalogs != null){
				for(File catalog : catalogs){
					if(catalog != null && catalog.isDirectory()){
						File[] slides = catalog.listFiles();
						String catalogCode = catalog.getName();
						SlideInfo slideInfo = null;
						ArrayList<SlideInfo> slideList = slideMap.get(catalogCode);
						if(slideList == null){
							slideList = new ArrayList<SlideInfo>();
						}
						
						for(File slide : slides){
							if(slide != null && slide.isFile()){
								slideInfo = new SlideInfo();
								slideInfo.setFilePath(slide.getName());
								slideInfo.setRootPath(catalogCode);
								slideInfo.setIndex(getFileIndex(slideInfo.getFilePath()));
								
								slideList.add(slideInfo);
							}
						}
						
						if(!slideList.isEmpty()){
							Collections.sort(slideList);
							slideMap.put(catalogCode, slideList);
						}
					}
				}
			}
			
		}
	}
	
	private static int getFileIndex(String fileName){
		int index = 0;
		if(!StringUtilities.isEmpty(fileName)){
			int beginIndex = fileName.lastIndexOf(indexSeperator);
			int endIndex = fileName.lastIndexOf(".");
			String indexStr = fileName.substring((beginIndex+1), endIndex);
			try{
				index = Integer.parseInt(indexStr);
			}
			catch(Exception e){
				index = 0;
			}
		}
		return index;
	}

	@POST
	@Produces("application/json")
	public ArrayList<SlideInfo> getSlidesByCatalogCode(@PathParam("catalog")String catalog){
		return getSlides(catalog);
	}
	
	public static void main(String[] args){
		loadSlides();
		System.out.println(" data map "+slideMap);
	}

}
